package com.epam.lunch.service;

import java.util.List;
import static java.lang.String.format;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.epam.lunch.domain.Food;
import com.epam.lunch.domain.Order;
import com.epam.lunch.domain.OrderItem;
import com.epam.lunch.ws.SimpleOrder;
import com.epam.lunch.ws.SimpleOrderItem;

public class JpaOrderRepository implements OrderRepository {

	private EntityManager manager;
	public JpaOrderRepository(EntityManager manager) {
		this.manager = manager;
	}
	
	@Override
	public void persistSimpleOrder(SimpleOrder simpleOrder) throws OrderException {
		EntityTransaction tx = manager.getTransaction();
		tx.begin();
		try {
			Order fullOrder = new Order();
			fullOrder.setPerson(simpleOrder.getPerson());
			
			for (SimpleOrderItem nextSimpleItem : simpleOrder.getItems()) {
				Food nextFood = findFoodById(nextSimpleItem.getFoodId());
				if (nextFood == null) {
					throw new OrderException("no food found with id:" + nextSimpleItem.getFoodId());
				}
				OrderItem nextFullItem = new OrderItem();
				nextFullItem.setQuantity(nextSimpleItem.getQuantity());
				nextFullItem.setFood(nextFood);
				manager.persist(nextFullItem);
				fullOrder.getItems().add(nextFullItem);
			}
			
			manager.persist(fullOrder);

			tx.commit();

		} catch (OrderException oe) {
			tx.rollback();
			throw oe;
		} catch(Exception e) {
			tx.rollback();
			e.printStackTrace();
		}
	}

	private Food findFoodById(long foodId) {
		return manager.find(Food.class, foodId);
	}

	@Override
	public void listAllOrders() {
		List<Order> resultList = manager.createQuery("Select o From Order o", Order.class).getResultList();
		for (Order next : resultList) {
			System.out.println("next Order: " + next.getPerson());
			for (OrderItem nextItem : next.getItems()) {
				System.out.println(format("  %3d : %-30s (%d)", nextItem.getQuantity(), nextItem.getFood().getName(), nextItem.getFood().getPrice()));
			}
		}
	}

}
